//
//  TOAFHttpUtils.m
//  IMChat
//
//  Created by CLSgGhost on 2021/6/20.
//  Copyright © 2021年 TeamOne. All rights reserved.
//

#import "TOAFHttpUtils.h"

@implementation TOAFHttpUtils

#pragma mark 获取用户token
+ (void)requestRCIMToken:(NSString *)userId
                withName:(NSString *)userName
         withPortraitUri:(NSString *)userPortraitUri
               withBlock:(HttpSuccess)block{
    
    NSString *urlstr = @"https://api-cn.ronghub.com/user/getToken.json";
    
    NSDate *date = [NSDate date];
    NSTimeInterval times =  [date timeIntervalSince1970];
    
    // 时间戳
    NSString *timestamp = [[NSString alloc] initWithFormat:@"%@",[NSString stringWithFormat:@"%.0f",times]];
    
    // 随机数
    NSString *nonce = [NSString stringWithFormat:@"%d",abs(arc4random())];
    
    // 系统分配的AppKey、Nonce、Timestamp三个字符串拼接好的字符串进行SHA1哈希计算
    NSString *signature = [self sha1:[NSString stringWithFormat:@"%@%@%@",AppSecret,nonce,timestamp]];
    
    NSLog([NSString stringWithFormat:@"%@%@%@",AppSecret,nonce,timestamp]);
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //((AFJSONResponseSerializer *)manager.responseSerializer).removesKeysWithNullValues = YES;
    
    // 每次请求 API接口时，均需要提供 4个 HTTP Request Header
    [manager.requestSerializer setValue:AppKey forHTTPHeaderField:@"App-Key"];
    [manager.requestSerializer setValue:nonce forHTTPHeaderField:@"Nonce"];
    [manager.requestSerializer setValue:timestamp forHTTPHeaderField:@"Timestamp"];
    [manager.requestSerializer setValue:signature forHTTPHeaderField:@"Signature"];
    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    
    NSLog(@"------请求头：%@",manager.requestSerializer.HTTPRequestHeaders);
    
    // 表单参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"userId"] = userId;
    parameters[@"name"] = userName;
    parameters[@"portraitUri"] = userPortraitUri;
    
    [manager POST:urlstr
       parameters:parameters
          success:^(NSURLSessionDataTask * _Nullable operation,id _Nullable responseObject){
              NSLog(@"token获取成功");
              //NSLog(@"%@",responseObject);
              
              NSError *error = nil;
              // Json转为NSData
              NSData *responseData = [NSJSONSerialization dataWithJSONObject:responseObject options:kNilOptions error:&error];
              // NSData转为NSDictionary
              NSDictionary *responseDict = [NSJSONSerialization
                                           JSONObjectWithData:responseData options:kNilOptions error:&error];
              // NSDictionary转为NSString
              NSString *token = [responseDict objectForKey:@"token"];
              [SAMKeychain setPassword:token forService:@"token" account:AppKey];
              block(token);
          }
          failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
              NSLog(@"token获取失败");
              //NSLog(@"%@",error);
              block(@"error");
          }];
}

/*使用下面方法需要导入 CommonCrypto/CommonDigest.h*/
// SHA1哈希计算
+ (NSString *)sha1:(NSString *)key
{
    NSData *data = [key dataUsingEncoding:NSUTF8StringEncoding];

//    const char *cstr = [key cStringUsingEncoding:NSUTF8StringEncoding];
//    NSData *data = [NSData dataWithBytes:cstr length:key.length];

    uint8_t digest[CC_SHA1_DIGEST_LENGTH];

    CC_SHA1(data.bytes, (unsigned int)data.length, digest);

    NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH *2];

    for(int i=0; i<CC_SHA1_DIGEST_LENGTH; i++) {
        [output appendFormat:@"%02x", digest[i]];
    }

    return output;

}

#pragma mark 验证用户登陆
+ (void)verifyUserLogin:(NSString *)userId
           withPassword:(NSString *)userPassword
              withBlock:(HttpSuccess)block{
    
    NSString *urlstr = @"https://qc56zp.fn.thelarkcloud.com/verifyUserLogin";
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    /*
     * 表单参数
     * @{@"userId":userId,
     *   @"userPassword":userPassword
     *  };
     */
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"userId"] = userId;
    parameters[@"userPassword"] = userPassword;
    
    NSError *error;
    NSData *body = [NSJSONSerialization dataWithJSONObject:parameters
                                                   options:kNilOptions
                                                     error:&error];
    
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:urlstr parameters:nil error:nil];
    
    [request addValue:@"application/json"forHTTPHeaderField:@"Content-Type"];
    
    // 设置请求体
    [request setHTTPBody:body];
    
    [[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *_Nonnull response, id _Nullable responseObject,NSError * _Nullable error){
        
        NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject
                                      options:kNilOptions error:&error];
        NSLog(@"-----登陆验证结果：%@", responseDict);
        // NSDictionary转为NSString
        NSString *code = [responseDict objectForKey:@"code"];
        if([code isEqualToString:@"200"]){
            NSLog(@"!!!!!成功！！！！！%@",code);
            [SAMKeychain setPassword:userId forService:@"userId" account:AppKey];
            [SAMKeychain setPassword:userPassword forService:@"userPassword" account:AppKey];
            block(@"success");
        }else{
            block(@"error");
        }
     }] resume];
}

#pragma mark 用户注册
+ (void)userRegister:(NSString *)userId
            withName:(NSString *)userName
        withPassword:(NSString *)userPassword
           withBlock:(HttpSuccess)block{
    
    NSString *urlstr = @"https://qc56zp.fn.thelarkcloud.com/addUserInfo";
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    /**
     * 表单参数
     * @{@"userId":userId,
     *   @"userName":userName,
     *   @"userPassword":userPassword,
     *   @"portraitUri":@""
     *  };
     */
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"userId"] = userId;
    parameters[@"userName"] = userName;
    parameters[@"userPassword"] = userPassword;
    parameters[@"portraitUri"] = @"null";
    parameters[@"userSex"] = @"null";
    
    NSError *error;
    NSData *body = [NSJSONSerialization dataWithJSONObject:parameters
                                                   options:kNilOptions
                                                     error:&error];
    
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:urlstr parameters:nil error:nil];
    
    [request addValue:@"application/json"forHTTPHeaderField:@"Content-Type"];
    
    // 设置请求体
    [request setHTTPBody:body];
    
    [[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *_Nonnull response, id _Nullable responseObject,NSError * _Nullable error){
        
        NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject
              options:kNilOptions error:&error];
        NSLog(@"-----注册验证结果：%@", responseDict);
        // NSDictionary转为NSString
        NSString *code = [responseDict objectForKey:@"code"];
        if([code isEqualToString:@"200"]){
            NSLog(@"!!!!!成功！！！！！%@",code);
            block(@"success");
        }else if([code isEqualToString:@"1001"]){
            block(@"error-1001");
        }else{
            block(@"error-1000");
        }
    }] resume];
    
}

#pragma mark 查找用户好友
+ (void)findUserFriends:(NSString *)userId
              withBlock:(HttpSuccess)block{
    
    NSString *urlstr = @"https://qc56zp.fn.thelarkcloud.com/findFriendsInfo";
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    /**
     * 表单参数
     * @{@"userId":userId};
     */
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"userId"] = userId;
    
    NSError *error;
    NSData *body = [NSJSONSerialization dataWithJSONObject:parameters
                                                   options:kNilOptions
                                                     error:&error];
    
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:urlstr parameters:nil error:nil];
    
    [request addValue:@"application/json"forHTTPHeaderField:@"Content-Type"];
    
    // 设置请求体
    [request setHTTPBody:body];
    
    [[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *_Nonnull response, id _Nullable responseObject,NSError * _Nullable error){
        
        NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject
                    options:kNilOptions error:&error];
        
        NSLog(@"-----查找好友ID结果：%@", responseDict);
        NSArray *friendIdList = [responseDict objectForKey:@"friendIdList"];
        NSArray *friendNameList = [responseDict objectForKey:@"friendNameList"];
        NSArray *friendProUriList = [responseDict objectForKey:@"friendProUriList"];
        
        NSMutableArray<FriendInfoModel *> *friendModelList = [NSMutableArray arrayWithCapacity:10];
        
        /** 给全局变量赋值. */
        AppDelegate *myDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
        
        for(int i=0; i<[friendIdList count]; i++){
            FriendInfoModel *friendModel = [[FriendInfoModel alloc]init];
            friendModel.friendId = friendIdList[i];
            friendModel.friendName = friendNameList[i];
            friendModel.friendPortraitUri = friendProUriList[i];
            
            [friendModelList addObject:friendModel];
            //NSLog(@"HTTP!!!%@",friendModelList[i].friendId);
        }
        
        myDelegate.friendModelList = friendModelList;
        
        // NSDictionary转为NSString
        NSString *code = [responseDict objectForKey:@"code"];
  
        if([code isEqualToString:@"200"]){
            //NSLog(@"!!!!!成功！！！！！%@",code);
            block(@"success");
        }else if([code isEqualToString:@"1002"]){
            block(@"error-1002");
        }else{
            block(@"error-1000");
        }
    }] resume];
}

#pragma mark 自己对别人发送好友请求
+ (void)sendAddNewFriendMessage:(RCContactNotificationMessage *)messageModel
                      withBlock:(HttpSuccess)block{
    
    NSString *urlstr = @"https://api-cn.ronghub.com/message/system/publish.json";
    
    NSDate *date = [NSDate date];
    NSTimeInterval times =  [date timeIntervalSince1970];
    
    // 时间戳
    NSString *timestamp = [[NSString alloc] initWithFormat:@"%@",[NSString stringWithFormat:@"%.0f",times]];
    
    // 随机数
    NSString *nonce = [NSString stringWithFormat:@"%d",abs(arc4random())];
    
    // 系统分配的AppKey、Nonce、Timestamp三个字符串拼接好的字符串进行SHA1哈希计算
    NSString *signature = [self sha1:[NSString stringWithFormat:@"%@%@%@",AppSecret,nonce,timestamp]];
    
    NSLog([NSString stringWithFormat:@"%@%@%@",AppSecret,nonce,timestamp]);
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //((AFJSONResponseSerializer *)manager.responseSerializer).removesKeysWithNullValues = YES;
    
    // 每次请求 API接口时，均需要提供 4个 HTTP Request Header
    [manager.requestSerializer setValue:AppKey forHTTPHeaderField:@"App-Key"];
    [manager.requestSerializer setValue:nonce forHTTPHeaderField:@"Nonce"];
    [manager.requestSerializer setValue:timestamp forHTTPHeaderField:@"Timestamp"];
    [manager.requestSerializer setValue:signature forHTTPHeaderField:@"Signature"];
    [manager.requestSerializer setValue:@"Application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    
    NSLog(@"------请求头：%@",manager.requestSerializer.HTTPRequestHeaders);
    
    NSDictionary *content = @{@"operation":messageModel.operation,
                              @"sourceUserId":messageModel.sourceUserId,
                              @"targetUserId":messageModel.targetUserId,
                              @"message":messageModel.message
                              };
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:content options:kNilOptions error:&error];
    
    NSString *jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    // 表单参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"fromUserId"] = @"syetem";
    parameters[@"objectName"] = @"RC:ContactNtf";
    parameters[@"toUserId"] = messageModel.targetUserId;
    parameters[@"content"] = jsonString;
    
    NSLog(@"------请求参数：%@",parameters);
    
    [manager POST:urlstr
       parameters:parameters
          success:^(NSURLSessionDataTask * _Nullable operation,id _Nullable responseObject){
              NSLog(@"好友请求发送成功");
              NSLog(@"%@",responseObject);
              block(@"success");
          }
          failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
              NSLog(@"好友请求发送失败");
              NSLog(@"%@",error);
              block(@"error");
          }];
}

#pragma mark 根据ID查找用户是否存在
+ (void)findUserIsExist:(NSString *)userId
           withBlock:(HttpSuccess)block{
    
    NSString *urlstr = @"https://qc56zp.fn.thelarkcloud.com/findUserInfoById";
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    /**
     * 表单参数
     * @{@"userId":userId};
     */
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"userId"] = userId;
    
    NSError *error;
    NSData *body = [NSJSONSerialization dataWithJSONObject:parameters
                                                   options:kNilOptions
                                                     error:&error];
    
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:urlstr parameters:nil error:nil];
    
    [request addValue:@"application/json"forHTTPHeaderField:@"Content-Type"];
    
    // 设置请求体
    [request setHTTPBody:body];
    
    [[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *_Nonnull response, id _Nullable responseObject,NSError * _Nullable error){
        
        NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject
                                                                     options:kNilOptions error:&error];
        
        NSLog(@"-----查找用户信息结果：%@", responseDict);
        
        // NSDictionary转为NSString
        NSString *code = [responseDict objectForKey:@"code"];
        NSLog(@"%@", code);
        //NSInteger count = [responseDict objectForKey:@"count"];
        if([code isEqualToString:@"200"]){
            NSLog(@"!!!!!成功！！！！！%@",code);
            block(@"success");
        }else{
            block(@"error-1000");
        }
    }] resume];
}

#pragma mark 根据ID查找用户信息
+ (void)findUserById:(NSString *)userId
           withBlock:(UserModelBlock)blockUserModel{
    
    NSString *urlstr = @"https://qc56zp.fn.thelarkcloud.com/findUserInfoById";
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    /**
     * 表单参数
     * @{@"userId":userId};
     */
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"userId"] = userId;
    
    NSError *error;
    NSData *body = [NSJSONSerialization dataWithJSONObject:parameters
                                                   options:kNilOptions
                                                     error:&error];
    
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:urlstr parameters:nil error:nil];
    
    [request addValue:@"application/json"forHTTPHeaderField:@"Content-Type"];
    
    // 设置请求体
    [request setHTTPBody:body];
    
    [[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *_Nonnull response, id _Nullable responseObject,NSError * _Nullable error){
        
        NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject
                       options:kNilOptions error:&error];
        
        //NSLog(@"-----查找用户信息结果：%@", responseDict);

        // NSDictionary转为NSString
        NSString *code = [responseDict objectForKey:@"code"];
        NSString *userName = [responseDict objectForKey:@"userName"];
        NSString *userPortraitUri = [responseDict objectForKey:@"userPortraitUri"];
        NSString *userSex = [responseDict objectForKey:@"userSex"];
        
        UserInfoModel *userModel = [[UserInfoModel alloc]
                                    initWithUserId:userId
                                    withUserName:userName
                                    withUserPortraitUri:userPortraitUri withUserSex:userSex];
        
        //NSInteger count = [responseDict objectForKey:@"count"];
        if([code isEqualToString:@"200"]){
            blockUserModel(userModel);
        }else{
            //NSLog(@"!!!!!失败！！！！！%@",code);
        }
    }] resume];
}

#pragma mark 修改用户信息（昵称、性别）
+ (void)updateUserById:(UserInfoModel *)userInfo{
    
    NSString *urlstr = @"https://qc56zp.fn.thelarkcloud.com/updateUserInfo";
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    /**
     * 表单参数
     */
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"userId"] = userInfo.userId;
    parameters[@"userName"] = userInfo.userName;
    parameters[@"userSex"] = userInfo.userSex;
    
    NSError *error;
    NSData *body = [NSJSONSerialization dataWithJSONObject:parameters
                                                   options:kNilOptions
                                                     error:&error];
    
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:urlstr parameters:nil error:nil];
    
    [request addValue:@"application/json"forHTTPHeaderField:@"Content-Type"];
    
    // 设置请求体
    [request setHTTPBody:body];
    
    [[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *_Nonnull response, id _Nullable responseObject,NSError * _Nullable error){
        
        NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&error];
        
        NSString *code = [responseDict objectForKey:@"code"];
        
        if([code isEqualToString:@"200"]){
            NSLog(@"!!!!!修改成功！！！！！%@",code);
        }else{
            //NSLog(@"!!!!!失败！！！！！%@",code);
        }
    }] resume];
}

#pragma mark 添加好友请求数据信息
+ (void)addNewFriendRequestInfo:(RCContactNotificationMessage *)messageModel{
    
    NSString *urlstr = @"https://qc56zp.fn.thelarkcloud.com/addNewFriendRequest";
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    /**
     * 表单参数
     * @{@"sourceUserId":messageModel.sourceUserId
     *   @"targetUserId":messageModel.targetUserId
     *   @"operation":messageModel.operation
     *   @"message":messageModel.message
     *  };
     */
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"sourceUserId"] = messageModel.sourceUserId;
    parameters[@"targetUserId"] = messageModel.targetUserId;
    parameters[@"operation"] = messageModel.operation;
    parameters[@"message"] = messageModel.message;
    
    NSError *error;
    NSData *body = [NSJSONSerialization dataWithJSONObject:parameters
                                                   options:kNilOptions
                                                     error:&error];
    
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:urlstr parameters:nil error:nil];
    
    [request addValue:@"application/json"forHTTPHeaderField:@"Content-Type"];
    
    // 设置请求体
    [request setHTTPBody:body];
    
    [[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *_Nonnull response, id _Nullable responseObject,NSError * _Nullable error){
        
        NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject
                                                                     options:kNilOptions error:&error];
        
        NSLog(@"-----添加好友请求数据信息结果：%@", responseDict);
        
        // NSDictionary转为NSString
        NSString *code = [responseDict objectForKey:@"code"];
        //NSInteger count = [responseDict objectForKey:@"count"];
        if([code isEqualToString:@"200"]){
            NSLog(@"!!!!!成功！！！！！%@",code);
            //block(@"success");
        }else if([code isEqualToString:@"1001"]){
            NSLog(@"!!!!!失败！！！！！%@",code);
            //block(@"error-1001");
        }else{
            NSLog(@"!!!!!失败！！！！！%@",code);
            //block(@"error-1000");
        }
    }] resume];
}

#pragma mark 查找好友请求数据信息
+ (void)findNewFiendRequestInfo:(NSString *)userId{
    
    NSString *urlstr = @"https://qc56zp.fn.thelarkcloud.com/findNewFriendRequestList";
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    /**
     * 表单参数
     * @{@"targetUserId":userId};
     */
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"targetUserId"] = userId;
    
    NSError *error;
    NSData *body = [NSJSONSerialization dataWithJSONObject:parameters
                                                   options:kNilOptions
                                                     error:&error];
    
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:urlstr parameters:nil error:nil];
    
    [request addValue:@"application/json"forHTTPHeaderField:@"Content-Type"];
    
    // 设置请求体
    [request setHTTPBody:body];
    
    [[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *_Nonnull response, id _Nullable responseObject,NSError * _Nullable error){
        
        NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject
                                                                     options:kNilOptions error:&error];
        
        NSLog(@"-----查询好友请求数据信息结果：%@", responseDict);
        
        // NSDictionary转为NSString
        NSString *code = [responseDict objectForKey:@"code"];
        NSArray *sourceUserIdList = [responseDict objectForKey:@"sourceUserIdList"];
        NSArray *operationList = [responseDict objectForKey:@"operationList"];
        NSArray *messageList = [responseDict objectForKey:@"messageList"];
        
        NSMutableArray<RCContactNotificationMessage *> *nFriendReqList = [NSMutableArray arrayWithCapacity:10];
        
        /** 给全局变量赋值. */
        AppDelegate *myDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
        
        for(int i=0; i<[sourceUserIdList count]; i++){
            RCContactNotificationMessage *nFReq = [[RCContactNotificationMessage alloc]init];
            nFReq.sourceUserId = sourceUserIdList[i];
            nFReq.operation = operationList[i];
            nFReq.message = messageList[i];
            
            [nFriendReqList addObject:nFReq];
            NSLog(@"HTTP!!!%@",nFriendReqList[i].sourceUserId);
        }
        
        myDelegate.nFriendReqList = nFriendReqList;
        
        if([code isEqualToString:@"200"]){
            NSLog(@"!!!!!成功！！！！！%@",code);
        }else if([code isEqualToString:@"1001"]){
            NSLog(@"!!!!!失败！！！！！%@",code);
        }else{
            NSLog(@"!!!!!失败！！！！！%@",code);
        }
    }] resume];
}

#pragma mark 同意添加好友关系
+ (void)acceptAddNewFriend:(NSString *)userId
              withFriendId:(NSString *)friendId
                 withBlock:(HttpSuccess)block{
    
    NSString *urlstr = @"https://qc56zp.fn.thelarkcloud.com/addNewFriend";
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    /**
     * 表单参数
     * @{@"userId":userId,
     *   @"friendId":friendId};
     */
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"userId"] = userId;
    parameters[@"friendId"] = friendId;
    
    NSError *error;
    NSData *body = [NSJSONSerialization dataWithJSONObject:parameters
                                                   options:kNilOptions
                                                     error:&error];
    
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:urlstr parameters:nil error:nil];
    
    [request addValue:@"application/json"forHTTPHeaderField:@"Content-Type"];
    
    // 设置请求体
    [request setHTTPBody:body];
    
    [[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *_Nonnull response, id _Nullable responseObject,NSError * _Nullable error){
        
        NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject
                                                                     options:kNilOptions error:&error];
        
        NSLog(@"-----添加好友信息结果：%@", responseDict);
        
        // NSDictionary转为NSString
        NSString *code = [responseDict objectForKey:@"code"];
        
        if([code isEqualToString:@"200"]){
            NSLog(@"!!!!!成功！！！！！%@",code);
            block(@"success");
        }else if([code isEqualToString:@"1001"]){
            NSLog(@"!!!!!失败！！！！！%@",code);
            block(@"error-1001");
        }else{
            NSLog(@"!!!!!失败！！！！！%@",code);
            block(@"error-1000");
        }
    }] resume];
}

#pragma mark 轻服务更新好友请求信息的operation
+ (void)updateAcceptRequest:(RCContactNotificationMessage *)messageModel{
    
    NSString *urlstr = @"https://qc56zp.fn.thelarkcloud.com/updateNFReqOperation";
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    /**
     * 表单参数
     * @{@"sourceUserId":messageModel.sourceUserId
     *   @"targetUserId":messageModel.targetUserId
     *   @"operation":messageModel.operation
     *  };
     */
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"sourceUserId"] = messageModel.sourceUserId;
    parameters[@"targetUserId"] = messageModel.targetUserId;
    parameters[@"operation"] = messageModel.operation;
    
    NSError *error;
    NSData *body = [NSJSONSerialization dataWithJSONObject:parameters
                                                   options:kNilOptions
                                                     error:&error];
    
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:urlstr parameters:nil error:nil];
    
    [request addValue:@"application/json"forHTTPHeaderField:@"Content-Type"];
    
    // 设置请求体
    [request setHTTPBody:body];
    
    [[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *_Nonnull response, id _Nullable responseObject,NSError * _Nullable error){
        
        NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject
                     options:kNilOptions error:&error];
        
        NSLog(@"-----更新好友请求数据信息结果：%@", responseDict);
        
        // NSDictionary转为NSString
        NSString *code = [responseDict objectForKey:@"code"];
        //NSInteger count = [responseDict objectForKey:@"count"];
        if([code isEqualToString:@"200"]){
            NSLog(@"!!!!!成功！！！！！%@",code);
            //block(@"success");
        }else if([code isEqualToString:@"1001"]){
            NSLog(@"!!!!!失败！！！！！%@",code);
            //block(@"error-1001");
        }else{
            NSLog(@"!!!!!失败！！！！！%@",code);
            //block(@"error-1000");
        }
    }] resume];
}

#pragma mark 创建群组
+ (void)createGroup:(NSMutableArray *)userIdList
            groupId:(NSString *)groupId
          withBolck:(HttpSuccess)block{
    
    NSString *urlstr = @"https://api-cn.ronghub.com/group/create.json";
    
    NSDate *date = [NSDate date];
    NSTimeInterval times =  [date timeIntervalSince1970];
    
    // 时间戳
    NSString *timestamp = [[NSString alloc] initWithFormat:@"%@",[NSString stringWithFormat:@"%.0f",times]];
    
    // 随机数
    NSString *nonce = [NSString stringWithFormat:@"%d",abs(arc4random())];
    
    // 系统分配的AppKey、Nonce、Timestamp三个字符串拼接好的字符串进行SHA1哈希计算
    NSString *signature = [self sha1:[NSString stringWithFormat:@"%@%@%@",AppSecret,nonce,timestamp]];
    
    NSLog([NSString stringWithFormat:@"%@%@%@",AppSecret,nonce,timestamp]);
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //((AFJSONResponseSerializer *)manager.responseSerializer).removesKeysWithNullValues = YES;
    
    // 每次请求 API接口时，均需要提供 4个 HTTP Request Header
    [manager.requestSerializer setValue:AppKey forHTTPHeaderField:@"App-Key"];
    [manager.requestSerializer setValue:nonce forHTTPHeaderField:@"Nonce"];
    [manager.requestSerializer setValue:timestamp forHTTPHeaderField:@"Timestamp"];
    [manager.requestSerializer setValue:signature forHTTPHeaderField:@"Signature"];
    [manager.requestSerializer setValue:@"Application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    
    NSLog(@"------请求头：%@",manager.requestSerializer.HTTPRequestHeaders);
    
    static dispatch_once_t once;
    
    for(NSString *userId in userIdList){
        // 表单参数
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        parameters[@"userId"] = userId;
        parameters[@"groupId"] = groupId;
        parameters[@"groupName"] = [NSString stringWithFormat:@"群组%@",groupId];
        
        NSLog(@"------请求参数：%@",parameters);
        
        [manager POST:urlstr
           parameters:parameters
              success:^(NSURLSessionDataTask * _Nullable operation,id _Nullable responseObject){
                  dispatch_once(&once,^{
                      block(groupId);
                      NSLog(@"只block一次");
                  });
              }
              failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                  dispatch_once(&once,^{
                      block(@"error");
                      NSLog(@"只block一次");
                  });
              }];
    }
    
}

#pragma mark 轻服务添加群组信息
+ (void)addGroupInfo:(NSMutableArray *)groupMemberList
               block:(HttpSuccess)block{
    
    NSString *urlstr = @"https://qc56zp.fn.thelarkcloud.com/addGroupInfo";
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    
    // 随机生成群组ID
    NSString *groupId = [NSString stringWithFormat:@"%d",(unsigned)(arc4random()%100000)+100000];
    
    // 群组名
    NSString *groupName = [NSString stringWithFormat:@"群组%@",groupId];
    
    /**
     * 表单参数
     * @{@"groupId":groupId,
     *   @"groupName":groupName,
     *   @"groupMemberList":groupMemberList};
     */
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"groupId"] = groupId;
    parameters[@"groupName"] = groupName;
    parameters[@"groupMemberList"] = groupMemberList;
    
    NSError *error;
    NSData *body = [NSJSONSerialization dataWithJSONObject:parameters
                                                   options:kNilOptions
                                                     error:&error];
    
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:urlstr parameters:nil error:nil];
    
    [request addValue:@"application/json"forHTTPHeaderField:@"Content-Type"];
    
    // 设置请求体
    [request setHTTPBody:body];
    
    [[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *_Nonnull response, id _Nullable responseObject,NSError * _Nullable error){
        
        NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject
                                                                     options:kNilOptions error:&error];
        
        NSLog(@"-----创建群组信息结果：%@", responseDict);
        
        // NSDictionary转为NSString
        NSString *code = [responseDict objectForKey:@"code"];
        NSString *groupId = [responseDict objectForKey:@"groupId"];
        
        if([code isEqualToString:@"200"]){
            NSLog(@"!!!!!成功！！！！！%@",code);
            block(groupId);
        }else if([code isEqualToString:@"1001"]){
            NSLog(@"!!!!!失败！！！！！%@",code);
            block(@"error-1001");
        }else{
            NSLog(@"!!!!!失败！！！！！%@",code);
            block(@"error-1000");
        }
    }] resume];
    
}

#pragma mark 通过群组ID查找群组信息
+ (void)findGroupInfoById:(NSString *)groupId
                    block:(GroupInfoModelBlock)block{
    
    NSString *urlstr = @"https://qc56zp.fn.thelarkcloud.com/findGroupById";
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    /**
     * 表单参数
     * @{@"groupId":groupId};
     */
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"groupId"] = groupId;
    
    NSError *error;
    NSData *body = [NSJSONSerialization dataWithJSONObject:parameters
                                                   options:kNilOptions
                                                     error:&error];
    
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:urlstr parameters:nil error:nil];
    
    [request addValue:@"application/json"forHTTPHeaderField:@"Content-Type"];
    
    // 设置请求体
    [request setHTTPBody:body];
    
    [[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *_Nonnull response, id _Nullable responseObject,NSError * _Nullable error){
        
        NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject
                                                                     options:kNilOptions error:&error];
        
        // NSDictionary转为NSString
        NSString *code = [responseDict objectForKey:@"code"];
        NSString *groupId = [responseDict objectForKey:@"groupId"];
        NSString *groupName = [responseDict objectForKey:@"groupName"];
        NSString *groupOwnerId = [responseDict objectForKey:@"groupOwnerId"];
        
        NSArray *groupMemberIdList = [responseDict objectForKey:@"groupMemberIdList"];
        
        GroupInfoModel *groupInfo = [[GroupInfoModel alloc]initWithGroupId:groupId
                                                                 groupName:groupName groupOwnerId:groupOwnerId groupMemberIdList:groupMemberIdList];
        
        //NSInteger count = [responseDict objectForKey:@"count"];
        if([code isEqualToString:@"200"]){
            block(groupInfo);
        }else{
            NSLog(@"!!!!!群组失败！！！！！%@",code);
        }
    }] resume];
}

#pragma mark 发送群系统消息
+ (void)sendGroupMessage:(NSString *)groupId
                 content:(RCGroupNotificationMessage *)groupMessage{
    
    NSString *urlstr = @"https://api-cn.ronghub.com/message/publish.json";
    
    NSDate *date = [NSDate date];
    NSTimeInterval times =  [date timeIntervalSince1970];
    
    // 时间戳
    NSString *timestamp = [[NSString alloc] initWithFormat:@"%@",[NSString stringWithFormat:@"%.0f",times]];
    
    // 随机数
    NSString *nonce = [NSString stringWithFormat:@"%d",abs(arc4random())];
    
    // 系统分配的AppKey、Nonce、Timestamp三个字符串拼接好的字符串进行SHA1哈希计算
    NSString *signature = [self sha1:[NSString stringWithFormat:@"%@%@%@",AppSecret,nonce,timestamp]];
    
    NSLog([NSString stringWithFormat:@"%@%@%@",AppSecret,nonce,timestamp]);
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //((AFJSONResponseSerializer *)manager.responseSerializer).removesKeysWithNullValues = YES;
    
    // 每次请求 API接口时，均需要提供 4个 HTTP Request Header
    [manager.requestSerializer setValue:AppKey forHTTPHeaderField:@"App-Key"];
    [manager.requestSerializer setValue:nonce forHTTPHeaderField:@"Nonce"];
    [manager.requestSerializer setValue:timestamp forHTTPHeaderField:@"Timestamp"];
    [manager.requestSerializer setValue:signature forHTTPHeaderField:@"Signature"];
    [manager.requestSerializer setValue:@"Application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    
    NSError *error;
    
    NSDictionary *content = @{@"operatorUserId":groupMessage.operatorUserId,
                              @"operation":groupMessage.operation,
                              @"data":groupMessage.data,
                              @"message":groupMessage.message
                              };
    
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:content options:kNilOptions error:&error];
    
    NSString *jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    // 表单参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"fromUserId"] = @"syetem";
    parameters[@"objectName"] = @"RC:GrpNtf";
    parameters[@"toGroupId"] = groupId;
    parameters[@"content"] = jsonString;
    
    NSLog(@"------请求参数：%@",parameters);
    
    [manager POST:urlstr
       parameters:parameters
          success:^(NSURLSessionDataTask * _Nullable operation,id _Nullable responseObject){
              NSLog(@"群组通知发送成功");
              NSLog(@"%@",responseObject);
          }
          failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
              NSLog(@"群组通知发送失败");
              NSLog(@"%@",error);
          }];
}

@end
